package at.ac.univie.ise;


import java.sql.Connection;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jooq.impl.Factory;

import at.ac.univie.ise.common.Constants;
import at.ac.univie.ise.common.DBAccess;
import at.ac.univie.ise.generator.LocationGenerator;
import at.ac.univie.ise.generator.PersonGenerator;
import at.ac.univie.ise.generator.VehicleGenerator;
import at.ac.univie.ise.schema.IseFactory;
import de.pyranja.util.DateUtils;

public class ISEFiller {

	// logger
	private final Log log = LogFactory.getLog(ISEFiller.class);

//	private Simulator sim;
	
	// database
	private DBAccess db;
	
	// entity storage
	private LocationGenerator locations;
	private PersonGenerator persons;
	private VehicleGenerator vehicles;
	
	public ISEFiller() {
		db = new DBAccess(Constants.DB_PROP_FILE);
		log.info("** prepared");
	}
	
	public void init() throws SQLException {
		log.info(">> initializing");
		Connection conn = db.openConnection();
		Factory f = new IseFactory(conn);
		locations = new LocationGenerator(f);
		db.releaseConnection(conn);
		log.info("<< initialized");
	}
	
	public void build() throws SQLException {
		log.info(">> filling");
		Connection conn = db.openConnection();
		Factory f = new IseFactory(conn);
		persons = new PersonGenerator(f);
		vehicles = new VehicleGenerator(f);
//		sim = new Simulator(db);
//		sim.simulate();
		log.info("<< filled");
	}
	
	public void free() {
		this.db.terminate();
		log.info("** teminated");
	}
	
	public static void main(String... args) {
		System.out.println("Starting...");
		Date start = new Date();
		ISEFiller run = null;
		try {
			run = new ISEFiller();
			run.init();
			run.build();
		} catch (Throwable t) {
			System.err.println("An exception occured while filling");
			t.printStackTrace(System.err);
		} finally {
			run.free();
		}
		DecimalFormat df = new DecimalFormat("0.00");
		double runTime = (new Date().getTime() - start.getTime()) * 1.0D / DateUtils.ONE_SEC_AS_MS;
		System.out.println("Generation took "+ df.format(runTime) +" seconds");
		System.out.println("Exiting...");
	}
}
